<?php
namespace App\Services;

use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;

class WebSocketService
{
    protected $server;
    protected $port = 9502;

    public function __construct()
    {
        $this->server = new Server("0.0.0.0", $this->port);

        $this->server->on('start', [$this, 'onStart']);
        $this->server->on('open', [$this, 'onOpen']);
        $this->server->on('message', [$this, 'onMessage']);
        $this->server->on('close', [$this, 'onClose']);
    }

    public function onStart(Server $server)
    {
        echo "WebSocket Server started at ws://0.0.0.0:{$this->port}\n";
    }

    public function onOpen(Server $server, Request $request)
    {
        echo "connection open: {$request->fd}\n";
    }

    public function onMessage(Server $server, Frame $frame)
    {
        echo "received message: {$frame->data}\n";
        // 处理消息逻辑
        $this->handleMessage($frame->fd, $frame->data);
    }

    public function onClose(Server $server, $fd)
    {
        echo "connection close: {$fd}\n";
    }

    protected function handleMessage($fd, $data)
    {
        $data = json_decode($data, true);
        switch ($data['type'] ?? '') {
            case 'auth':
                // 处理认证
                $this->handleAuth($fd, $data);
            break;
            case 'admin_notify':
                // 处理管理员通知
                $this->handleAdminNotify($fd, $data);
            break;
            default:
                $this->server->push($fd, json_encode([
                    'type' => 'error',
                    'message' => 'Unsupported message type'
                ]));
        }
    }

    protected function handleAuth($fd, $data)
    {
        // 实现认证逻辑
        $this->server->push($fd, json_encode([
            'type' => 'auth',
            'status' => 'success'
        ]));
    }

    public function start()
    {
    $this->server->start();
    }
}
